import os
import logging
import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from libreofficeDockerCall import router, BASE_TEMP_DIR, BASE_OUTPUT_DIR

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler()
    ]
)
logger = logging.getLogger("libreoffice-converter")

# 创建FastAPI应用
app = FastAPI(
    title="LibreOffice文档转换API",
    description="将各种文档格式转换为PDF的API服务",
    version="1.0.0"
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许所有源，生产环境中应该限制
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 包含路由
app.include_router(router)

@app.on_event("startup")
async def startup_event():
    """应用启动时执行的操作"""
    # 确保基础目录存在
    os.makedirs(BASE_TEMP_DIR, exist_ok=True)
    os.makedirs(BASE_OUTPUT_DIR, exist_ok=True)
    logger.info(f"应用启动，临时目录: {BASE_TEMP_DIR}, 输出目录: {BASE_OUTPUT_DIR}")

@app.get("/")
def read_root():
    """API根路径，返回欢迎信息"""
    return {"message": "欢迎使用LibreOffice文档转换API", "version": "1.0.0"}

if __name__ == "__main__":
    # 启动FastAPI服务
    uvicorn.run(app, host="0.0.0.0", port=8001) 